package edu.nf.supermarket.config;

import edu.nf.supermarket.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * @author yjj
 * @date 2025-05-19
 */
@Configuration
@EnableWebMvc
@ComponentScan("edu.nf.supermarket.web")
public class MvcConfig implements WebMvcConfigurer {
    /**
     * 全局跨域设置
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").
                allowedOrigins("*").
                allowedMethods("*").
                allowedHeaders("*").
                exposedHeaders("*");
//       允许Cookie跨域
//               allowCredentials(true).

    }

    /**
     * 注册拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")         // 拦截所有请求
                .excludePathPatterns("/user/login", "/user/register", "/alipay/notify", "/alipay/return", "/static/**");  // 放行登录和注册接口，静态资源访问
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        //实例化内部资源视图解析器
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        //设置前缀
        viewResolver.setPrefix("/static/");
        //设置后缀
        viewResolver.setSuffix(".html");
        //注册视图解析器
        registry.viewResolver(viewResolver);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/photo/**")
                .addResourceLocations("file:D:\\Java\\supermarketPrudect\\supermarket-product\\supermarket-web\\src\\main\\webapp\\static\\photo\\");
        // 映射 /static/** 到 /static/ 下的所有资源
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/", "file:src/main/webapp/static/");

        //映射静态资源的请求前缀地址
        registry.addResourceHandler("/page/**")
                //指定本地静态资源的路径(本地路径不能使用通配符, 但是可以指定多个, 在参数后加逗号即可)
                .addResourceLocations("/static/",
                        "static/js/", "/static/css/");
        // 配置 favicon.ico
        registry.addResourceHandler("/favicon.ico")
                .addResourceLocations("classpath:/static/log.ico");
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorParameter(false)
                .ignoreAcceptHeader(true)
                .useRegisteredExtensionsOnly(false)
                .defaultContentType(MediaType.APPLICATION_JSON);
    }

}
